package com.neiquan.backstage.admin_user.web.action;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.neiquan.backstage.admin_user.AdminUserService;
import com.neiquan.backstage.common.util.BackendErrorCode;
import com.neiquan.backstage.common.util.CommonResp;
import com.neiquan.backstage.common.util.ExtraSpringHibernateTemplate;
import com.neiquan.backstage.common.util.Paging;
import com.neiquan.backstage.common.util.Sessions;
import com.neiquan.backstage.pub.bsc.dao.po.AdminUser;

@Controller
@RequestMapping(value = "adminUser", produces = { "text/json;charset=UTF-8" })
public class AdminUserAction {
	private static Class<?> poc = AdminUser.class;
	@Autowired
	private ExtraSpringHibernateTemplate extraSpringHibernateTemplate;
	@Autowired
	private AdminUserService adminUserService;

	@ResponseBody
	@RequestMapping("list")
	public String list(int pageIndex, int pageSize, HttpSession session) {
		AdminUser loginedUser = (AdminUser) Sessions.getLoginedUser(session);
		Criterion criterion = Restrictions.eq("memberId", loginedUser.getMemberId());
		DetachedCriteria queryListCriteria = ExtraSpringHibernateTemplate.C.build(poc, Order.desc("userId"), criterion);
		DetachedCriteria queryCountCriteria = ExtraSpringHibernateTemplate.C.buildRowCount(poc, criterion);
		Paging<?> paging = extraSpringHibernateTemplate.findPageByCriteria(queryListCriteria, queryCountCriteria, 0, Integer.MAX_VALUE);
		return CommonResp.buildSuccessResp(paging).toJsonString();
	}

	@ResponseBody
	@RequestMapping("all")
	public String all(HttpSession session) {
		AdminUser loginedUser = (AdminUser) Sessions.getLoginedUser(session);
		DetachedCriteria detached = DetachedCriteria.forClass(poc);
		detached.add(Restrictions.eq("memberId", loginedUser.getMemberId()));
		return CommonResp.buildSuccessResp(extraSpringHibernateTemplate.findAllByCriteria(detached)).toJsonString();
	}

	@ResponseBody
	@RequestMapping(value = "updateMyPwd")
	public String updateMyPwd(String newPassword, String password, HttpSession session) {
		AdminUser loginedUser = (AdminUser) Sessions.getLoginedUser(session);
		AdminUser toUpdate = adminUserService.queryByAccount(loginedUser.getAccount(), loginedUser.getMemberId());
		if (!toUpdate.getPassword().equals(password)) {
			return CommonResp.buildErrorResp(BackendErrorCode.account_password_not_match).toJsonString();
		}
		toUpdate.setPassword(newPassword);
		extraSpringHibernateTemplate.getHibernateTemplate().update(toUpdate);
		return CommonResp.buildSuccessResp().toJsonString();
	}

	@ResponseBody
	@RequestMapping(value = "updatePwd")
	public String updatePwd(String newPassword, Integer id) {
		AdminUser toUpdate = adminUserService.queryById(id);
		toUpdate.setPassword(newPassword);
		extraSpringHibernateTemplate.getHibernateTemplate().update(toUpdate);
		return CommonResp.buildSuccessResp().toJsonString();
	}

	@ResponseBody
	@RequestMapping(value = "queryDetail")
	public String queryDetail(Integer id) {
		JSONObject resp = new JSONObject();
		resp.put("adminUser", adminUserService.queryById(id));
		resp.put("adminUserPermission", null);
		return CommonResp.buildSuccessResp(resp).toJsonString();
	}

	@ResponseBody
	@RequestMapping(value = "remove")
	public String remove(Integer id) {
		AdminUser toDelete = adminUserService.queryById(id);
		if (toDelete == null) {
			return CommonResp.buildErrorResp(BackendErrorCode.not_exist).toJsonString();
		}
		extraSpringHibernateTemplate.getHibernateTemplate().delete(toDelete);
		return CommonResp.buildSuccessResp().toJsonString();
	}

	@ResponseBody
	@RequestMapping(value = "search")
	public String search(String realname, String phone, HttpSession session) {
		AdminUser loginedUser = (AdminUser) Sessions.getLoginedUser(session);
		List<Criterion> criterions = new ArrayList<>();
		criterions.add(Restrictions.eq("memberId", loginedUser.getMemberId()));
		if (StringUtils.isNoneBlank(realname)) {
			criterions.add(Restrictions.like("realname", "%" + realname + "%"));
		}
		if (StringUtils.isNoneBlank(phone)) {
			criterions.add(Restrictions.like("phone", "%" + phone + "%"));
		}
		Criterion criterion = Restrictions.and(criterions.toArray(new Criterion[] {}));
		DetachedCriteria queryListCriteria = ExtraSpringHibernateTemplate.C.build(poc, Order.desc("userId"), criterion);
		DetachedCriteria queryCountCriteria = ExtraSpringHibernateTemplate.C.buildRowCount(poc, criterion);
		Paging<?> paging = extraSpringHibernateTemplate.findPageByCriteria(queryListCriteria, queryCountCriteria, 0, Integer.MAX_VALUE);
		return CommonResp.buildSuccessResp(paging).toJsonString();
	}

	@ResponseBody
	@RequestMapping(value = "add")
	public String add(String account, String password, String realname, String phone, String department, HttpSession session) {
		AdminUser loginedUser = (AdminUser) Sessions.getLoginedUser(session);
		Integer memberId = loginedUser.getMemberId();
		if (adminUserService.queryByAccount(account, memberId) != null) {
			return CommonResp.buildErrorResp(BackendErrorCode.account_exist).toJsonString();
		}
		AdminUser toSave = new AdminUser();
		toSave.setMemberId(memberId);
		toSave.setSuperUser(AdminUser.super_user_no);
		toSave.setAccount(account);
		toSave.setPassword(password);
		toSave.setDtCreat(System.currentTimeMillis());
		toSave.setRealname(realname);
		toSave.setPhone(phone);
		toSave.setDepartment(department);
		toSave.setRoleId(-1);
		extraSpringHibernateTemplate.getHibernateTemplate().save(toSave);
		return CommonResp.buildSuccessResp().toJsonString();
	}

	@ResponseBody
	@RequestMapping(value = "edit")
	public String edit(Integer id, String realname, String phone, String department) {
		AdminUser toUpdate = adminUserService.queryById(id);
		if (null == toUpdate) {
			return CommonResp.buildErrorResp(BackendErrorCode.account_not_exist).toJsonString();
		}
		toUpdate.setRealname(realname);
		toUpdate.setPhone(phone);
		toUpdate.setDepartment(department);
		extraSpringHibernateTemplate.getHibernateTemplate().update(toUpdate);
		return CommonResp.buildSuccessResp().toJsonString();
	}
}
